import { action, computed, makeObservable, observable } from "mobx"

let id = 0


// const state = observable({
//   apples: [],
//   isPicking: false
// })

// const current = computed(() => state.apples.filter(a => !a.isEaten))

// const currentWeight = computed(() => {
//   return current.reduce((total, c) => total += c.weight, 0)
// })

// const ate = computed(() => state.apples.filter(a => a.isEaten))

// const ateWeight = computed(() => ate.reduce((total, c) => total += c.weight, 0))

// const pickApple = action(state => {
//   state.isPicking = true;
//   fetch('https://hacker-news.firebaseio.com/v0/jobstories.json')
//     .then(res => {
//         /** 备注这里的url只是测试用的，这个是之前hackernews的api, 这里只是确保接口是通的，至于数据还是自己mock */
//         let weight = Math.floor(200 + Math.random() * 50);
//         state.isPicking = false;
//         state.apples.push({
//             id: ++id,
//             weight: weight,
//             isEaten: false
//         });
//     });
// })

export default class Store {
  apples = []
  isPicking = false

  constructor() {
    makeObservable(this, {
      apples: observable,
      isPicking: observable,
      currentWeight: computed,
      ate: computed,
      ateWeight: computed,
      pickApple: action,
      eatApple: action
    })
  }

  get current() {
    return this.apples.filter(a => !a.isEaten)
  }
  get currentWeight() {
    return this.current.reduce((total, c) => total += c.weight, 0)
  }
  get ate() {
    return this.apples.filter(a => a.isEaten)
  }
  get ateWeight() {
    return this.ate.reduce((total, c) => total += c.weight, 0)
  }

  pickApple() {
    return new Promise((resolve) => {
      this.isPicking = true;
      setTimeout(() => {
        let weight = Math.floor(200 + Math.random() * 50);
        this.isPicking = false;
        this.buttonText = '摘苹果';
        this.apples.push({
            id: ++id,
            weight: weight,
            isEaten: false
        });
        resolve()
      }, 1000)
    })
  }

  eatApple(id) {
    this.apples.forEach(ap => {
      if (ap.id === id) {
        ap.isEaten = true
      }
    })
  }
}